import json
import requests
import pandas as pd

from tools.wrappers import deco_retry
from tools.tools import reformat_timestamp

history_url = 'https://history.deribit.com/api/v2'
base_url = 'https://www.deribit.com/api/v2'


@deco_retry(retry=5, retry_sleep=15)
def get_expired_instruments(currency='BTC', kind='option'):
    url = f'{history_url}/public/get_instruments?currency={currency}&kind={kind}&expired=true'
    res = requests.get(url)
    df = pd.DataFrame(json.loads(res.text)['result'])
    df.sort_values(by=['expiration_timestamp', 'instrument_name'], inplace=True)

    timezone = '+0000'
    df['expiration_datetime'] = pd.to_datetime(df['expiration_timestamp'], unit='ms').dt.tz_localize(
        'UTC').dt.tz_convert(timezone)
    df['expiration_datetime'] = df['expiration_datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
    df['creation_datetime'] = pd.to_datetime(df['creation_timestamp'], unit='ms').dt.tz_localize('UTC').dt.tz_convert(
        timezone)
    df['creation_datetime'] = df['creation_datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
    return df


def get_active_instruments(currency='BTC', kind='option'):
    url = f'{history_url}/public/get_instruments?currency={currency}&kind={kind}'
    res = requests.get(url)
    df = pd.DataFrame(json.loads(res.text)['result'])
    df.sort_values(by=['expiration_timestamp', 'instrument_name'], inplace=True)

    timezone = '+0000'
    df['expiration_datetime'] = pd.to_datetime(df['expiration_timestamp'], unit='ms').dt.tz_localize(
        'UTC').dt.tz_convert(timezone)
    df['expiration_datetime'] = df['expiration_datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
    df['creation_datetime'] = pd.to_datetime(df['creation_timestamp'], unit='ms').dt.tz_localize('UTC').dt.tz_convert(
        timezone)
    df['creation_datetime'] = df['creation_datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
    return df


@deco_retry(retry=5, retry_sleep=15)
def get_instruments(currency='BTC', kind='option'):
    df1 = get_expired_instruments(currency, kind)
    df2 = get_active_instruments(currency, kind)
    df = pd.concat([df1, df2], ignore_index=True)
    df.drop_duplicates(subset=['instrument_name'], ignore_index=True, inplace=True)
    return df


@deco_retry(retry=1000, retry_sleep=60)
def get_last_trades_by_instrument(instrument_name='BTC-27OCT23-27500-C', count=50):
    all_data_df_list = []

    url = f'{history_url}/public/get_last_trades_by_instrument?instrument_name={instrument_name}&count={count}&include_old=true'
    res = requests.get(url)
    if '{"reason":"wrong format","param":"instrument_name"}' in res.text:
        print(f'{instrument_name}"reason":"wrong format","param":"instrument_name"')
        return None
    data = pd.DataFrame(json.loads(res.text)['result']['trades'])
    if data.empty:
        print(f'{instrument_name}无交易记录')
        return None

    data.sort_values(by=['trade_seq'], ascending=False, inplace=True)
    data = reformat_timestamp(data)
    all_data_df_list.append(data)

    has_more_flag = json.loads(res.text)['result']['has_more']
    while has_more_flag:
        end_seq = min(data['trade_seq'])
        url = f'{history_url}/public/get_last_trades_by_instrument?instrument_name={instrument_name}&end_seq={end_seq}&count={count}&include_old=true'
        res = requests.get(url)
        data = pd.DataFrame(json.loads(res.text)['result']['trades'])
        if data.empty:
            print(f'{instrument_name}无交易记录')
            has_more_flag = False
        else:
            data.sort_values(by=['trade_seq'], ascending=False, inplace=True)
            data = reformat_timestamp(data)
            all_data_df_list.append(data)
            has_more_flag = json.loads(res.text)['result']['has_more']

    all_data = pd.concat(all_data_df_list)
    all_data.drop_duplicates(subset=['trade_seq'], inplace=True)
    return all_data


if __name__ == '__main__':
    get_last_trades_by_instrument(instrument_name='BTC-27OCT23-27500-C', count=50)
